package com.samphanie.security.security.oauth.granter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.samphanie.common.enums.ResultCode;
import com.samphanie.common.execetion.ApiException;
import com.samphanie.common.service.IRedisService;
import com.samphanie.common.utils.RequestHolder;
import com.samphanie.security.security.oauth.sms.SmsCodeAuthenticationToken;
import com.samphanie.security.domain.Captcha;
import com.samphanie.security.validation.properties.CodeConstant;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
public class SmsCodeTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "sms";
    private final AuthenticationManager authenticationManager;
    private IRedisService redisService;

    public SmsCodeTokenGranter(AuthenticationManager authenticationManager,
                               AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory, IRedisService redisService) {
        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.redisService = redisService;
    }

    protected SmsCodeTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                  ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        HttpServletRequest request = RequestHolder.getHttpServletRequest();

        if (ObjectUtil.isNull(request)) {
            throw new ApiException(ResultCode.USER_ERROR_A0410);
        }
        String key = request.getHeader(CodeConstant.DEFAULT_PARAMETER_KEY);
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String mobile = parameters.get(CodeConstant.DEFAULT_PARAMETER_NAME_MOBILE);
        String code = parameters.get(CodeConstant.DEFAULT_PARAMETER_NAME_CODE);

        if (StrUtil.isBlank(code)) {
            throw new ApiException("请输入验证码！");
        }

        Captcha codeFromRedis = null;
        // 从Redis里读取存储的验证码信息
        try {
            codeFromRedis = (Captcha) redisService.get(CodeConstant.SMS_CODE_KEY + key);
        } catch (Exception e) {
            throw new ApiException("验证码不存在！");
        }

        if (ObjectUtil.isNull(codeFromRedis) || codeFromRedis.isExpired()) {
            throw new ApiException("验证码不存在或已过期！");
        }

        // 比较输入的验证码是否正确
        if (!StrUtil.equalsIgnoreCase(code, codeFromRedis.getCode())) {
            throw new ApiException("验证码不正确！");
        }

        redisService.del(CodeConstant.SMS_CODE_KEY + mobile);

        Authentication userAuth = new SmsCodeAuthenticationToken(mobile);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException | BadCredentialsException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        }
        // If the username/password are wrong the spec says we should send 400/invalid grant

        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
